package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.form.model.FormField;
import com.ccp.dev.form.model.FormTable;
import com.ccp.dev.form.service.FormTableService;
import com.ccp.dev.workflow.model.ActDefModel;
import com.ccp.dev.workflow.model.BpmNewFlowTrigger;
import com.ccp.dev.workflow.model.BpmUserCondition;
import com.ccp.dev.workflow.service.ActDefModelService;
import com.ccp.dev.workflow.service.BpmNewFlowTriggerService;
import com.ccp.dev.workflow.service.BpmUserConditionService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassDescribe:
 * 触发新流程接口控制层
 * @author :wangcheng
 * Date: 2019-07-12
 */
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/bpmNewFlowTrigger")
@Controller
@Action(ownermodel = SysAuditModelType.PROCESS_MANAGEMENT)
public class BpmNewFlowTriggerController extends SysBaseController {
    @Resource
    private BpmNewFlowTriggerService bpmNewFlowTriggerService;
    @Resource
    private BpmUserConditionService bpmUserConditionService;
    @Resource
    private ActDefModelService actDefModelService;
    @Resource
    private FormTableService formTableService;

    /**
     * 触发新流程配置编辑页面跳转
     * @param model ui模型
     * @param request http请求
     * @return 跳转路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/edit")
    @Action(description = "触发新流程配置编辑页面跳转", detail = "触发新流程配置编辑页面跳转")
    public String viewEdit(Model model, HttpServletRequest request) {
        String id = RequestUtil.getString(request, "id");
        String nodeId = RequestUtil.getString(request, "nodeId");
        String flowKey = RequestUtil.getString(request, "flowKey");
        String procDefId = RequestUtil.getString(request, "procDefId");

        // 获取人员设置
        List<BpmUserCondition> startUserConditions = bpmUserConditionService.getTriggerNewFlowStartUserConditions(procDefId, nodeId);
        BpmNewFlowTrigger bpmNewFlowTrigger;
        if (StringUtil.isEmpty(id)) {
            bpmNewFlowTrigger = bpmNewFlowTriggerService.getByFlowKeyNodeId(flowKey, nodeId);
        }else {
            bpmNewFlowTrigger = bpmNewFlowTriggerService.getOneById(id);
        }

        model.addAttribute("bpmNewFlowTrigger", bpmNewFlowTrigger);
        model.addAttribute("nodeId", nodeId);
        model.addAttribute("startUserConditions", JSONArray.fromObject(startUserConditions).toString());
        model.addAttribute("flowKey", flowKey);
        model.addAttribute("procDefId", procDefId);
        return getAutoView();
    }

    /**
     * 删除触发新流程配置
     * @param request http请求
     * @return 返回结果封装对象
     */
    @RequestMapping("/del")
    @Action(description = "删除触发新流程配置", execOrder = ActionExecOrder.BEFORE, detail = "删除触发新流程配置")
    @ResponseBody
    public ResultData del(HttpServletRequest request) {
        try {
            String[] ids = RequestUtil.getStringAryByStr(request, "id");
            bpmNewFlowTriggerService.delByIds(ids);
            return getResultDataSuccess("delete.success");
        } catch (Exception e) {
            e.printStackTrace();
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 保存或者更新新流程跳转配置对象
     * @param bpmNewFlowTrigger 触发新流程配置对象
     * @return 返回结果封装类
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @Action(description = "保存或者更新新流程跳转配置对象", detail = "保存或者更新新流程跳转配置对象")
    @ResponseBody
    public ResultData save(BpmNewFlowTrigger bpmNewFlowTrigger) {
        String resultMsg;
        bpmNewFlowTrigger.setJsonMaping(StringEscapeUtils.unescapeHtml4(bpmNewFlowTrigger.getJsonMaping()));
        bpmNewFlowTrigger.setTriggerJson(StringEscapeUtils.unescapeHtml4(bpmNewFlowTrigger.getTriggerJson()));
        try {
            if (StringUtil.isEmpty(bpmNewFlowTrigger.getId())) {
                bpmNewFlowTrigger.setId(UUIDUtils.getUUIDFor32());
                bpmNewFlowTriggerService.add(bpmNewFlowTrigger);
                resultMsg = "save.success";
            } else {
                bpmNewFlowTriggerService.update(bpmNewFlowTrigger);
                resultMsg = "update.success";
            }
            return getResultDataSuccess(resultMsg);
        } catch (Exception e) {
            e.printStackTrace();
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 通过流程key 获取表单信息
     * @param request http请求
     * @return 表单属性封装集合
     */
    @RequestMapping("/getTableTreeByDefKey")
    @Action(description = "通过流程key 获取表单信息", detail = "通过流程key 获取表单信息")
    @ResponseBody
    public ResultData getTableTreeByDefKey(HttpServletRequest request) {
        String defKey = RequestUtil.getString(request, "defKey");
        String type = RequestUtil.getString(request, "type", "trigger");

        ActDefModel actDefModel = actDefModelService.getMainByDefKey(defKey);
        // 根据模型id获取流程绑定表
        FormTable table;
        try {
            table = formTableService.getByProcDefId(actDefModel.getProcDefId());
        } catch (Exception e) {
            return getResultDataError(e.getMessage());
        }

        // 读取表中 属性字段列表
        List<FormField> fieldList =  handleTableToFieldTree(table);

        JSONArray jsonArray = new JSONArray();
        for (FormField field : fieldList) {
            String icon = "";
            JSONObject json = new JSONObject();
            json.accumulate("style", type)
                    .accumulate("fieldId", field.getFieldId())
                    .accumulate("tableId", field.getTableId())
                    .accumulate("fieldType", field.getFieldType())
                    .accumulate("fieldName", field.getFieldName())
                    .accumulate("fieldDesc", field.getFieldDesc() + "(" + field.getFieldType() + ")")
                    .accumulate("icon", icon);
            jsonArray.add(json);
        }

        return getResultDataSuccess("operation.success",jsonArray.toString());
    }

    /**
     * 读取表中 属性字段列表
     * @param table 表对象
     * @return 属性列表
     */
    private List<FormField> handleTableToFieldTree(FormTable table) {
        List<FormField> fieldList = new ArrayList<>();
        FormField mainField = getFieldByTable(table);
        fieldList.add(mainField);
        fieldList.addAll(table.getFieldList());

        if(BeanUtils.isNotEmpty(table.getSubTableList())){
            for(FormTable subTable :table.getSubTableList()){
                fieldList.add(getFieldByTable(subTable));
                fieldList.addAll(subTable.getFieldList());
            }
        }
        return fieldList;
    }

    /**
     * 获取属性
     * @param table 表数据
     * @return 表单属性
     */
    private FormField getFieldByTable(FormTable table) {
        FormField field = new FormField();
        field.setTableId(table.getMainTableId());
        field.setFieldId(table.getTableId());
        field.setFieldName(table.getTableName());
        field.setFieldDesc(table.getTableDesc());
        field.setFieldType("table");
        field.setType(table.getIsMain());
        return field;
    }

}
